package org.hiro;

import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.util.xmlb.XmlSerializationException;
import com.intellij.util.xmlb.XmlSerializer;
import org.hiro.configuration.Configuration;
import org.hiro.configuration.ConfigurationPanel;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public class GenerateBuilderComponent implements ProjectComponent, Configurable, JDOMExternalizable {
    private Configuration configuration = new Configuration();
    private ConfigurationPanel configurationPanel;

    @NotNull
    public String getComponentName() {
        return "GenerateBuilder";
    }

    public void initComponent() {
    }

    public void disposeComponent() {
    }

    public void projectOpened() {
    }

    public void projectClosed() {
    }

    public void apply() throws ConfigurationException {
        configuration = configurationPanel.getConfiguration();
        GenerateBuilderContext.setConfiguration(configuration);
    }

    public void reset() {
        configurationPanel.setConfiguration(configuration);
    }

    public JComponent createComponent() {
        return configurationPanel = new ConfigurationPanel(configuration);
    }

    public void disposeUIResources() {
        configurationPanel = null;
    }

    public boolean isModified() {
        return !configuration.equals(configurationPanel.getConfiguration());
    }

    public String getDisplayName() {
        return "Generate Builder";
    }

    public String getHelpTopic() {
        return null;
    }

    public Icon getIcon() {
        return null; //IconLoader.getIcon("org/hiro/icon.png");
    }

    public void readExternal(Element element) throws InvalidDataException {
        try {
            configuration = XmlSerializer.deserialize(element, Configuration.class);
            GenerateBuilderContext.setConfiguration(configuration);
        } catch (XmlSerializationException e) {
            e.printStackTrace();
        }
    }

    public void writeExternal(Element element) throws WriteExternalException {
        try {
            XmlSerializer.serialize(configuration);
        } catch (XmlSerializationException e) {
            e.printStackTrace();
        }
    }
}
